##########################################
## Copyright 2012-2013 Ceruti Francesco
##
##
## This file is part of LiSP (Linux Show Player).
##
## LiSP (Linux Show Player) is free software: you can redistribute it and/or modify
## it under the terms of the GNU Lesser General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## LiSP (Linux Show Player) is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU Lesser General Public License for more details.
##
## You should have received a copy of the GNU Lesser General Public License
## along with LiSP (Linux Show Player).  If not, see <http://www.gnu.org/licenses/>.
##########################################

import socket
import threading


class Master:

    def __init__(self, masterPort, slavePort):
        self.slavePort = slavePort
        self.slave = []
        self.sSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sSocket.bind(('', masterPort))
        self.sSocket.listen(16)
        self.acceptThread = threading.Thread(target=self.listen)
        self.acceptThread.setDaemon(True)
        self.acceptThread.start()

    def listen(self):
        while(True):
            try:
                conn, addr = self.sSocket.accept()
                data = conn.recv(1024)
                if(data == bytes('SLAVE', 'UTF-8')):
                    self.slave.append(addr[0])
                conn.close()
            except:
                pass

    def sendAction(self, action):
        for sl in self.slave:
            try:
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                sock.connect((sl, self.slavePort))
                sock.send(bytes(action, 'UTF-8'))
                sock.close()
            except:
                self.slave.remove(sl)
